package net.chrone.quickpayapi.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.chrone.quickpayapi.mapper.OrgPayChannelMapper;
import net.chrone.quickpayapi.mapper.PayChannelMapper;
import net.chrone.quickpayapi.model.Order;
import net.chrone.quickpayapi.model.PayChannel;
import net.chrone.quickpayapi.model.PayChannelExample;
import net.chrone.quickpayapi.model.PayChannelExample.Criteria;
import net.chrone.quickpayapi.model.PayChannelKey;
import net.chrone.quickpayapi.service.PayChannelService;
import net.chrone.quickpayapi.util.Constant;
@Service
public class PayChannelServiceImpl implements PayChannelService {
	
	@Autowired
	private PayChannelMapper payChannelMapper;
	@Autowired
	private OrgPayChannelMapper orgPayChannelMapper;
	
	@Override
	public PayChannel getChannle(Order order) {
		PayChannel channel = getChannelByOrgId(order);//根据机构号获取通道
		if(null==channel){
			channel = getDefaultChannel(order);//获取默认通道
		}
		return channel;
	}

	private PayChannel getChannelByOrgId(Order order) {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("orgId", order.getOrgId());//
		params.put("payType", Constant.CHNL_TP_WECHAT);//暫時默認微信
		params.put("orderTp", order.getOrderTp());//
		params.put("chnlTp", order.getTranTp());
		return orgPayChannelMapper.getChannelByOrgId(params);
	}
	
	private PayChannel getDefaultChannel(Order order) {
		PayChannelExample example = new PayChannelExample();
		Criteria criteria = example.createCriteria();
		criteria.andPayTypeEqualTo(Constant.CHNL_TP_WECHAT);
		criteria.andChnlTpEqualTo(order.getTranTp());
		criteria.andOrderTpEqualTo(order.getOrderTp());
		criteria.andStatusEqualTo(1);
		example.setOrderByClause(" priority desc ");
		List<PayChannel> payChannels = payChannelMapper.selectByExample(example);
		if(payChannels!=null&&payChannels.size()>0){
			return payChannels.get(0);
		}
		return null;
	}

	@Override
	public PayChannel find(Order order) {
		PayChannelKey key = new PayChannelKey();
		key.setCode(order.getPayChannelId());
		key.setPayType(Constant.CHNL_TP_WECHAT);
		key.setChnlTp(order.getTranTp());
		key.setOrderTp(order.getOrderTp());
		return payChannelMapper.selectByPrimaryKey(key);
	}


}
